import { getProp } from '@/components/cms/utils'
import { InputNumber, Slider, type InputNumberProps, type SliderProps } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref, type PropType } from 'vue'
import { formState } from '../mixins/useState'
import type { JsonSchema, Slots } from '../types'

export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    slots: {
      type: Object as PropType<Slots>,
      default: () => undefined
    }
  },
  setup(props, ctx) {
    const inputValue = ref(props?.schema.defaultValue ?? 2)

    const _props = Object.assign({ showInput: true }, props.schema.props) as { showInput?: boolean }
    const handleChange = () => {
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      }
      const value = {
        path: props.schema.field,
        value: Number(inputValue.value)
      }
      ctx.emit('valueChange', value)
    }
    const handleObBlur = () => {
      inputValue.value = inputValue.value ?? 0
      handleChange()
    }
    onMounted(() => {
      nextTick(() => {
        const value = getProp(formState.model, props.schema.field as string).value as number
        inputValue.value = value
      })
    })
    return () => {
      return (
        <div class=" radius-field__wrapper">
          <Slider
            {...((props.schema?.props ?? {}) as SliderProps)}
            class="header-slider"
            v-model={[inputValue.value, 'value']}
            onChange={() => handleChange()}
          />
          <InputNumber
            class={!_props?.showInput ? 'hidden' : ''}
            {...((props.schema?.props ?? {}) as InputNumberProps)}
            keyboard={false}
            controls={false}
            onBlur={() => handleObBlur()}
            v-model={[inputValue.value, 'value']}
            onChange={() => handleChange()}
          ></InputNumber>
        </div>
      )
    }
  }
})
